export function formatBackTime(time: string) {
    if (time) {
        const unixtimestamp = new Date(time);
        const year = unixtimestamp.getFullYear();
        const month = '0' + (unixtimestamp.getMonth() + 1);
        const date = '0' + unixtimestamp.getDate();
        // const hour = '0' + unixtimestamp.getHours();
        // const minute = '0' + unixtimestamp.getMinutes();
        // const second = '0' + unixtimestamp.getSeconds();
        return year + '-' + month.substring(month.length - 2, month.length) 
            + '-' + date.substring(date.length - 2, date.length);
            // + ' ' + hour.substring(hour.length - 2, hour.length) 
            // + ':' + minute.substring(minute.length - 2, minute.length) 
            // + ':' + second.substring(second.length - 2, second.length);
    } else {
        return 'YY-MM-DD';
    }
}

export function checkMobile(str: string) {
    const re = /^1\d{10}$/;
    if (re.test(str)) {
        return true;
    } else {
        return false;
    }
}

export function checkEmail(str: string) {
    const re = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
    if (re.test(str)) {
        return true;
    } else {
        return false;
    }
}

export function SetCookie(name: string, value: string) {
    const exp = new Date();
    // 过期时间 2小时
    exp.setTime(exp.getTime() + 60 * 1000 * 120);  
    document.cookie = name + '=' + escape(value) + ';expires=' + exp.toUTCString();
}

export function GetCookie(key: string) {
    const arg = key + '=';
    const alen = arg.length;
    const clen = document.cookie.length;
    let i = 0;
    while (i < clen) {
        const j = i + alen;
        if (document.cookie.substring(i, j) === arg) {
            return getCookieVal(j);
        }
        i = document.cookie.indexOf(' ', i) + 1;
        if (i === 0) {
            break;
        }
    }
    return null;
}

function getCookieVal(offset: number) {
    let endstr = document.cookie.indexOf(';', offset);
    if (endstr === -1) {
        endstr = document.cookie.length;
    }
    return unescape(document.cookie.substring(offset, endstr));
}

export function DeleteCookie(key: string) {
    const exp = new Date();
    exp.setTime(exp.getTime() - 1);
    const cval = GetCookie(key);
    if (cval != null) {
        document.cookie = key + '=' + cval + ';domain=.lovebuy.shop;path=/;expires=' + exp.toUTCString();
    }
}
